package controllers

import (
	"blog-server/app/common/request"
	"blog-server/app/common/response"
	"blog-server/app/services"
	"blog-server/global"
	"github.com/gin-gonic/gin"
)

func (backendControllers *backendControllers) AdminRegister(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		response.ValidateFail(c, request.GetErrorMsg(form, err))
		global.App.Log.Error("参数校验失败")
		return
	}
	err, user := services.AdminService.AdminRegister(form)
	if err != nil {
		global.App.Log.Error("插入数据库失败")
		response.BusinessFail(c, err.Error())
		return
	} else {
		response.Success(c, user)
	}
}

func (backendControllers *backendControllers) AdminLogin(c *gin.Context) {
	var form request.Login
	if err := c.ShouldBind(&form); err != nil {
		response.ValidateFail(c, request.GetErrorMsg(form, err))
		global.App.Log.Error("参数校验失败")
		return
	}
	bool := VerifyCaptcha(form.CaptchaId, form.Captcha)
	if !bool {
		response.ValidateFail(c, "验证码错误")
		global.App.Log.Error("验证码错误")
		return
	}
	if err, user := services.AdminService.AdminLogin(form); err != nil {
		global.App.Log.Error("登陆失败")
		response.BusinessFail(c, err.Error())
		return
	} else {
		token, err, _ := services.JwtService.CreateToken(services.AppGuardName, user)
		if err != nil {
			global.App.Log.Error("生成token失败")
			response.BusinessFail(c, err.Error())
			return
		} else {
			response.Success(c, token)
		}
	}
}
